<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Http\Model\News;
use App\Helpers\SuccessResponse;
use App\Helpers\ValidatorResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Constant;

class NewsController extends Controller{

	public function __construct(){

	}

	public function detail($id){
		$validate = Validator::make(array('id' => $id), [
			'id' => 'required|integer|min:1',
		]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$news_model = new News(); 
			$news_data = $news_model->where('id', $id)->get()->toArray();
			if(0 == count($news_data)){
				return SuccessResponse::handler("No News[id=$id] Found.");
			}else{
				$related_news = DB::select('select * from news where id <>'.$id.' and category_id='.$news_data[0]['category_id'].' order by id desc limit 3');
				$related_news = json_decode(json_encode($related_news), true);
				foreach ($related_news as &$value) {
					$value['create_time_ago'] = $this->_getNewsCreateDate($value['created_at']);
				}
				$news_data[0]['create_time_ago'] = $this->_getNewsCreateDate($news_data[0]['created_at']);
				$rtn = [
					'detail' => $news_data,
					'related_news' => $related_news,
				];
				return SuccessResponse::handler($rtn);
			}
		}
	}


	// is_page      whether to pagenating
	// show_page 	 show current_page, total_count, total_page
	// current_page
	// page_count   how many rows per page
	// order_by     order by which fields, default id desc
	// news_status  -1:all, 0:draft
	public function listNews(Request $request){
		$is_page = intval($request->input('is_page')) == 1 ? 1 : 0;
		$show_page = intval($request->input('show_page')) == 1 ? 1 : 0;
		$current_page = intval($request->input('current_page'));
		$current_page = $current_page > 1 ? $current_page : 1;
		$page_count = intval($request['page_count']);
		$page_count = $page_count > 0 ? $page_count : 20;
		$order_by = json_decode($request->input('order_by'), true);
		$news_status = json_decode($request->input('news_status'), true);
		if(0 == count($news_status)){
			$news_status = array(
				Constant::TFEX_NEWS_STATUS_DRAFT,
				Constant::TFEX_NEWS_STATUS_PUBLISHED,
			);
		}else{
			$news_status = array_values($news_status);
		}
		$keywords = trim(strval($request->input('keywords')));
		if(0 != count($order_by)){
			$order_by_arr = array();
			foreach ($order_by as $key => $value) {
				if($value == 'desc' || $value == 'asc'){
					array_push($order_by_arr, $key.' '.$value);
				}else{
					continue;
				}
			}
			$order_by = implode(',', $order_by_arr);
		}else{
			$order_by = 'id desc';
		}

		$news_model = new News();
		if($is_page){
			$data_sql = 'select * from news where 1=1';
			if($news_status){
				$data_sql .= ' and status in ('.implode(',', $news_status).')';
			}
			if(0 != strlen($keywords)){
				$data_sql .= ' and ( title like "%'.$keywords.'%" or author like "%'.$keywords.'%" )';
			}
			$data_sql .= ' order by '.$order_by;
			$limit_start = ($current_page - 1) * $page_count;
			$data_sql .= ' limit '.$limit_start.','.$page_count;
			$news_data = DB::select($data_sql);
			$page_info = array(
				'total' => count($news_data),
				'total_page' => 1,
			);
			if($show_page){
				$count_sql = 'select count(*) as total from news where 1=1';
				if($news_status){
					$count_sql .= ' and status in ('.implode(',', $news_status).')';
				}
				if(0 != strlen($keywords)){
					$count_sql .= ' and ( title like "%'.$keywords.'%" or author like "%'.$keywords.'%" )';
				}
				$news_count = DB::select($count_sql);
				$news_count = json_decode(json_encode($news_count), true);
				$page_info = array(
					'total' => $news_count[0]['total'],
					'total_page' => ceil($news_count[0]['total'] / $page_count),
				);
			}
		}else{
			$data_sql = 'select * from news where 1=1';
			if($news_status){
				$data_sql .= ' and status in ('.implode(',', $news_status).')';
			}
			if(0 != strlen($keywords)){
				$data_sql .= ' and ( title like "%'.$keywords.'%" or author like "%'.$keywords.'%" )';
			}
			$data_sql .= ' order by '.$order_by;
			$data_sql .= ' limit 0,999';
			$news_data = DB::select($data_sql);
			$page_info = array(
				'total' => count($news_data),
				'total_page' => 1,
			);
		}
		$news_data = json_decode(json_encode($news_data), true);
		// $category_data = DB::select('select * from category where category_status <> '.Constant::TFEX_CATEGORY_STATUS_DELETE);
		$category_data = DB::select('select * from category');
		$category_data = json_decode(json_encode($category_data), true);
		$category_id_names = [];
		foreach ($category_data as $value) {
			$category_id_names[$value['id']] = $value['category_name'];
		}
		foreach ($news_data as &$value) {
			$value['content_no_dom'] = htmlspecialchars_decode(strip_tags($value['content']));
			$value['content_no_dom_sub_200'] = substr($value['content_no_dom'], 0, 200);
			$value['create_time_ago'] = $this->_getNewsCreateDate($value['created_at']);
			$value['category_name'] = isset($category_id_names[$value['category_id']]) ? $category_id_names[$value['category_id']] : 'Unknown Article Category';
		}
		$rtn_data = array(
			'where' => array(
				'is_page' => $is_page,
				'show_page' => $show_page,
				'current_page' => $current_page,
				'page_count' => $page_count,
				'order_by' => $order_by,
				'news_status' => $news_status,
				'keywords' => $keywords,
			),
			'data' => $news_data,
			'show_page' => $page_info,
		);
		return SuccessResponse::handler($rtn_data);
	}

	public function add(Request $request){
		$validate = Validator::make($request->all(), [
			'title' => 'required|string',
			'author' => 'required|string',
			'content' => 'required|string',
			'banner' => 'required|string',
            'category_id' => 'required|integer|min:1',
            'status' => 'required|integer|min:1',
            'handler' => 'required|integer|min:1',
        ]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$news_model = new News();
			$news_model->title = $request->input('title');
			$news_model->author = $request->input('author');
			$news_model->content = $request->input('content');
			$news_model->banner = $request->input('banner');
			$news_model->category_id = $request->input('category_id');
			$news_model->status = $request->input('status');
			$news_model->handler = $request->input('handler');
			$news_model->scan_times = 0;
			try{
				$news_id = $news_model->save();
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$news_data['id'] = $news_model->id;
			return SuccessResponse::handler($news_data);
		}
	}

	public function edit(Request $request){
		$validate = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
			'title' => 'required|string',
			'author' => 'required|string',
			'content' => 'required|string',
			'banner' => 'required|string',
            'category_id' => 'required|integer|min:1',
            'status' => 'required|integer|min:1',
            'handler' => 'required|integer|min:1',
        ]);
        if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$news_model = new News();
			$news_data = array(
				'title' => $request->input('title'),
				'author' => $request->input('author'),
				'content' => $request->input('content'),
				'banner' => $request->input('banner'),
				'category_id' => $request->input('category_id'),
				'status' => $request->input('status'),
				'handler' => $request->input('handler'),
			);
			try{
				$news_id = $news_model->where('id', $request->input('id'))->update($news_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$news_data['id'] = $request->input('id');
			return SuccessResponse::handler($news_data);
		}
	}

	public function delete(Request $request){
		$news_ids = json_decode($request->input('id'), true);
		if(0 == count($news_ids)){
			return ValidatorResponse::handler('['.Constant::EC_NO_VALIDATE_NEWS_IDS.'] No validate news id or ids privided.');
		}else{
			$news_model = new News();
			$update_data = array(
				'status' => Constant::TFEX_NEWS_STATUS_DELETE,
			);
			try{
				$news_model->whereIn('id', array_values($news_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $news_ids));
		}
	}

	public function publish(Request $request){
		$news_ids = json_decode($request->input('id'), true);
		if(0 == count($news_ids)){
			return ValidatorResponse::handler('['.Constant::EC_NO_VALIDATE_NEWS_IDS.'] No validate news id or ids privided.');
		}else{
			$news_model = new News();
			$update_data = array(
				'status' => Constant::TFEX_NEWS_STATUS_PUBLISHED,
			);
			try{
				$news_model->whereIn('id', array_values($news_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $news_ids));
		}
	}

	public function draft(Request $request){
		$news_ids = json_decode($request->input('id'), true);
		if(0 == count($news_ids)){
			return ValidatorResponse::handler('['.Constant::EC_NO_VALIDATE_NEWS_IDS.'] No validate news id or ids privided.');
		}else{
			$news_model = new News();
			$update_data = array(
				'status' => Constant::TFEX_NEWS_STATUS_DRAFT,
			);
			try{
				$news_model->whereIn('id',  array_values($news_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $news_ids));
		}
	}

	private function _getNewsCreateDate($create_time_str){
		$create_time_timestamp = strtotime($create_time_str);
		$today_timestamp = strtotime('today');
		if($create_time_timestamp >= $today_timestamp){
			$rtn = 'Today';
		}else{
			$duration = intval($today_timestamp - $create_time_timestamp);
			$duration_days = intval($duration / 86400);
			if($duration / 86400 != $duration_days){
				$duration_days++;
			}
			switch($duration_days){
				case 1: 
					$rtn = 'Yesterday';
					break;
				case 2:
				case 3:
				case 4:
				case 5:
				case 6:
					$rtn = $duration_days.' days ago';
					break;
				case 7:
					$rtn = 'A week ago';
					break;
				default:
					$rtn = substr($create_time_str, 0, 10);
			}
		}
		return $rtn;
	}

}
